﻿<?php
header ( 'Content-type:text/html;charset=utf-8' );
date_default_timezone_set('PRC');
include_once   '../sdk/acp_service.php';
include_once '../ZZYMessage/Message.php';
/**
 * 交易说明：	前台类交易成功才会发送后台通知。后台类交易（有后台通知的接口）交易结束之后成功失败都会发通知。
 *              为保证安全，涉及资金类的交易，收到通知后请再发起查询接口确认交易成功。不涉及资金的交易可以以通知接口respCode=00判断成功。
 *              未收到通知时，查询接口调用时间点请参照此FAQ：https://open.unionpay.com/ajweb/help/faq/list?id=77&level=0&from=0
 */

$logger = com\unionpay\acp\sdk\LogUtil::getLogger();
$logger->LogInfo($_POST ['orderId']."代收回调: " . com\unionpay\acp\sdk\createLinkString ( $_POST, false, true ));
			
if (isset ( $_POST ['signature'] )) {
	
	$checkResult = com\unionpay\acp\sdk\AcpService::validate ( $_POST ) ? '验签成功' : '验签失败';
	
	$logger->LogInfo($_POST ['orderId']."代收回调".$checkResult.com\unionpay\acp\sdk\SDKConfig::getSDKConfig()->version);
	if(!com\unionpay\acp\sdk\AcpService::validate ( $_POST )){
		$message = new com\unionpay\acp\message\Message(['accountsid'=>"8126c72e85ea153f086b513c002ac2af",'token'=>"dd01e7ef6ba384b0438099c15f776909"]);
		$RandParam=$_POST["orderId"].",".'代收交易查询失败';
		$message -> SendSms('67b509eb875242c3a1bfcfcc895ef29a','309743',$RandParam,"15334509852",0);
		return ;
	}
	$respCode = $_POST ['respCode'];
	//判断respCode=00、A6后，对涉及资金类的交易，请再发起查询接口查询，确定交易成功后更新数据库。
	if($respCode=="00"){
		$params = array(
				//以下信息非特殊情况不需要改动
				'version' => com\unionpay\acp\sdk\SDKConfig::getSDKConfig()->version,		  //版本号
				'encoding' => 'utf-8',		  //编码方式
				'signMethod' => com\unionpay\acp\sdk\SDKConfig::getSDKConfig()->signMethod,		  //签名方法
				'txnType' => '00',		      //交易类型	
				'txnSubType' => '00',		  //交易子类
				'bizType' => '000000',		  //业务类型
				'accessType' => '0',		  //接入类型
				'channelType' => '07',		  //渠道类型

				//TODO 以下信息需要填写
				'orderId' => $_POST["orderId"],	//请修改被查询的交易的订单号，8-32位数字字母，不能含“-”或“_”，此处默认取demo演示页面传递的参数
				'merId' => com\unionpay\acp\sdk\SDKConfig::getSDKConfig()->merId,	    //商户代码，请改自己的测试商户号，此处默认取demo演示页面传递的参数
				'txnTime' => $_POST["txnTime"],	//请修改被查询的交易的订单发送时间，格式为YYYYMMDDhhmmss，此处默认取demo演示页面传递的参数
			);

		com\unionpay\acp\sdk\AcpService::sign ( $params ); // 签名
		$url = com\unionpay\acp\sdk\SDKConfig::getSDKConfig()->singleQueryUrl;
		$logger->LogInfo($_POST ['orderId']."代收回调查询交易状态");
		$result_arr = com\unionpay\acp\sdk\AcpService::post ( $params, $url);
		if(count($result_arr)<=0) { //没收到200应答的情况
			$message = new com\unionpay\acp\message\Message(['accountsid'=>"8126c72e85ea153f086b513c002ac2af",'token'=>"dd01e7ef6ba384b0438099c15f776909"]);
			$RandParam=$_POST["orderId"].",".'代收交易查询失败';
			$message -> SendSms('67b509eb875242c3a1bfcfcc895ef29a','309743',$RandParam,"15334509852",0);
			return;
		}

		if (!com\unionpay\acp\sdk\AcpService::validate ($result_arr) ){
			$logger->LogInfo($_POST ['orderId']."代收回调查询交易状态应答报文验签失败");
			$message = new com\unionpay\acp\message\Message(['accountsid'=>"8126c72e85ea153f086b513c002ac2af",'token'=>"dd01e7ef6ba384b0438099c15f776909"]);
			$RandParam=$_POST["orderId"].",".'代收交易查询失败';
			$message -> SendSms('67b509eb875242c3a1bfcfcc895ef29a','309743',$RandParam,"15334509852",0);
			return;
		}

		$logger->LogInfo($_POST ['orderId']."代收回调查询交易状态应答报文验签成功");
		if ($result_arr["respCode"] == "00"){
			if ($result_arr["origRespCode"] == "00"){
				//交易成功
				$logger->LogInfo($_POST ['orderId']."代收回调查询交易状态交易成功");
				//TODO
				$mysqlHost=com\unionpay\acp\sdk\SDKConfig::getSDKConfig()->mysqlHost;
				$mysqlPort=com\unionpay\acp\sdk\SDKConfig::getSDKConfig()->mysqlPort;
				$mysqlDbname=com\unionpay\acp\sdk\SDKConfig::getSDKConfig()->mysqlDbname;
				$mysqlUser=com\unionpay\acp\sdk\SDKConfig::getSDKConfig()->mysqlUser;
				$mysqlPassword=com\unionpay\acp\sdk\SDKConfig::getSDKConfig()->mysqlPassword;
				$dbh = new PDO('mysql:host='.$mysqlHost.';port='.$mysqlPort.';dbname='.$mysqlDbname, $mysqlUser, $mysqlPassword);  
				$orderId=substr($_POST ['orderId'], 0, 12);
				$payMonth=substr($_POST ['orderId'], 26, strlen($_POST['orderId'])-26);
				//查询月供代收信息
				$sql = "SELECT * from `jdc_order_month_pay` where `orderid`=:orderid and `pay_month` =:payMonth";  
				$stmt = $dbh->prepare($sql);  
				$stmt->execute(array(':orderid'=>$orderId,':payMonth'=>$payMonth));  
				$payMonthData = $stmt->fetch(PDO::FETCH_ASSOC);
				if($payMonthData['status']==1){
					return;
				}
				

				
				//修改月供代收状态
				$payMoney=$payMonthData['pay_money']+round($_POST["settleAmt"]/100);
				if(intval($payMoney)>=intval($payMonthData['money'])){
					$sql ="UPDATE `jdc_order_month_pay` set `status`=:status,`pay_money`=:payMoney where `orderid`=:orderid and `pay_month` =:payMonth";
					$stmt = $dbh->prepare($sql);  
					$stmt->execute(array(':status'=>1,':payMoney'=>$payMoney,':orderid'=>$orderId,':payMonth'=>$payMonth));  
				}else{
					$sql ="UPDATE `jdc_order_month_pay` set `pay_money`=:payMoney where `orderid`=:orderid and `pay_month` =:payMonth";
					$stmt = $dbh->prepare($sql);  
					$stmt->execute(array(':payMoney'=>$payMoney,':orderid'=>$orderId,':payMonth'=>$payMonth));
				}
				
				
				

				//查询客户信息
				$sql = "SELECT * from `jdc_user` where `id`=:id";  
				$stmt = $dbh->prepare($sql);  
				$stmt->execute(array(':id'=>$payMonthData['uid']));  
				$userData = $stmt->fetch(PDO::FETCH_ASSOC);
				//查询收款信息
				$sql = "SELECT * from `jdc_order_pay` where `orderid`=:orderid";  
				$stmt = $dbh->prepare($sql);  
				$stmt->execute(array(':orderid'=>$orderId));  
				$payData = $stmt->fetchAll(PDO::FETCH_ASSOC);
				$money=0;
				foreach($payData as $val){
					$money+=$val['money'];
				}
				$sql = "INSERT INTO `jdc_order_pay` (`orderid` ,`uid` ,`pay_month` ,`status` ,`money` ,`paymoney`,`create_time`)VALUES (:orderid, :uid,:pay_month, :status, :money, :paymoney,:create_time)"; 
				$stmt = $dbh->prepare($sql); 
				$stmt->execute(array(':orderid'=>$orderId,':uid'=>$payMonthData['uid'],':pay_month'=>$payMonthData['pay_month'],':status'=>1,':money'=>round($_POST["settleAmt"]/100),':paymoney'=>$money+round($_POST["settleAmt"]/100),':create_time'=>time()));  
				$logger->LogInfo($_POST ['orderId']."代收修改数据库成功");
				//发送短信
				$mobilephone=$userData['tel'];
				$RandParam=$userData['fullanme'].",".substr($userData['banknum'],-4).','.date('Y-m-d H:i:s').','.round($_POST["settleAmt"]/100).',023-81307688';
				$message = new com\unionpay\acp\message\Message(['accountsid'=>"8126c72e85ea153f086b513c002ac2af",'token'=>"dd01e7ef6ba384b0438099c15f776909"]);
				$message -> SendSms('67b509eb875242c3a1bfcfcc895ef29a','297085',$RandParam,$mobilephone,0);
				$logger->LogInfo($_POST ['orderId']."代收短信提醒发送成功");
				

			} else if ($result_arr["origRespCode"] == "03"
					|| $result_arr["origRespCode"] == "04"
					|| $result_arr["origRespCode"] == "05"){
				//后续需发起交易状态查询交易确定交易状态
				//TODO
				$logger->LogInfo($_POST ['orderId']."代收回调查询交易状态交易处理中，请稍微查询。");
				$message = new com\unionpay\acp\message\Message(['accountsid'=>"8126c72e85ea153f086b513c002ac2af",'token'=>"dd01e7ef6ba384b0438099c15f776909"]);
				$RandParam=$_POST["orderId"].",".'代收交易查询失败';
				$message -> SendSms('67b509eb875242c3a1bfcfcc895ef29a','309743',$RandParam,"15334509852",0);
			} else {
				//其他应答码做以失败处理
				//TODO
				$logger->LogInfo($_POST ['orderId']."代收回调查询交易状态交易失败");
				$message = new com\unionpay\acp\message\Message(['accountsid'=>"8126c72e85ea153f086b513c002ac2af",'token'=>"dd01e7ef6ba384b0438099c15f776909"]);
				$RandParam=$_POST["orderId"].",".'代收交易查询显示代收失败';
				$message -> SendSms('67b509eb875242c3a1bfcfcc895ef29a','309743',$RandParam,"15334509852",0);
			}
		} else if ($result_arr["respCode"] == "03"
				|| $result_arr["respCode"] == "04"
				|| $result_arr["respCode"] == "05" ){
			//后续需发起交易状态查询交易确定交易状态
			//TODO
			$logger->LogInfo($_POST ['orderId']."代收回调查询交易状态处理超时，请稍微查询。");
			$message = new com\unionpay\acp\message\Message(['accountsid'=>"8126c72e85ea153f086b513c002ac2af",'token'=>"dd01e7ef6ba384b0438099c15f776909"]);
			$RandParam=$_POST["orderId"].",".'代收交易查询失败';
			$message -> SendSms('67b509eb875242c3a1bfcfcc895ef29a','309743',$RandParam,"15334509852",0);
		} else {
			//其他应答码做以失败处理
			//TODO
			$logger->LogInfo($_POST ['orderId']."代收交易查询失败");
			$message = new com\unionpay\acp\message\Message(['accountsid'=>"8126c72e85ea153f086b513c002ac2af",'token'=>"dd01e7ef6ba384b0438099c15f776909"]);
			$RandParam=$_POST["orderId"].",".'代收交易查询失败';
			$message -> SendSms('67b509eb875242c3a1bfcfcc895ef29a','309743',$RandParam,"15334509852",0);
		}
	}else{
		//其他应答码做以失败处理
		//TODO
		$logger->LogInfo($_POST ['orderId']."代收回调显示代收失败：". $_POST ['respMsg']);

		$mysqlHost=com\unionpay\acp\sdk\SDKConfig::getSDKConfig()->mysqlHost;
		$mysqlPort=com\unionpay\acp\sdk\SDKConfig::getSDKConfig()->mysqlPort;
		$mysqlDbname=com\unionpay\acp\sdk\SDKConfig::getSDKConfig()->mysqlDbname;
		$mysqlUser=com\unionpay\acp\sdk\SDKConfig::getSDKConfig()->mysqlUser;
		$mysqlPassword=com\unionpay\acp\sdk\SDKConfig::getSDKConfig()->mysqlPassword;
		$dbh = new PDO('mysql:host='.$mysqlHost.';port='.$mysqlPort.';dbname='.$mysqlDbname, $mysqlUser, $mysqlPassword);  
		$orderId=substr($_POST ['orderId'], 0, 12);
		$payMonth=substr($_POST ['orderId'], 26, strlen($_POST['orderId'])-26);
		//查询月供代收信息
		$sql = "SELECT * from `jdc_order_month_pay` where `orderid`=:orderid and `pay_month` =:payMonth";  
		$stmt = $dbh->prepare($sql);  
		$stmt->execute(array(':orderid'=>$orderId,':payMonth'=>$payMonth));  
		$payMonthData = $stmt->fetch(PDO::FETCH_ASSOC);

		//查询客户信息
		$sql = "SELECT * from `jdc_user` where `id`=:id";  
		$stmt = $dbh->prepare($sql);  
		$stmt->execute(array(':id'=>$payMonthData['uid']));  
		$userData = $stmt->fetch(PDO::FETCH_ASSOC);
		//发送短信
		$mobilephone=$userData['tel'];
		$RandParam=$userData['fullanme'].",".substr($userData['banknum'],-4).','.date('Y-m-d H:i:s').',023-81307688';
		$message = new com\unionpay\acp\message\Message(['accountsid'=>"8126c72e85ea153f086b513c002ac2af",'token'=>"dd01e7ef6ba384b0438099c15f776909"]);
		$message -> SendSms('67b509eb875242c3a1bfcfcc895ef29a','297113',$RandParam,$mobilephone,0);

		$message = new com\unionpay\acp\message\Message(['accountsid'=>"8126c72e85ea153f086b513c002ac2af",'token'=>"dd01e7ef6ba384b0438099c15f776909"]);
		$RandParam=$_POST["orderId"].",".'代收回调显示代收失败';
		$message -> SendSms('67b509eb875242c3a1bfcfcc895ef29a','309743',$RandParam,"15334509852",0);
	}

} else {
	$logger->LogInfo($_POST ['orderId']."代收回调签名为空 ");
	$message = new com\unionpay\acp\message\Message(['accountsid'=>"8126c72e85ea153f086b513c002ac2af",'token'=>"dd01e7ef6ba384b0438099c15f776909"]);
	$RandParam=$_POST["orderId"].",".'代收回调签名为空';
	$message -> SendSms('67b509eb875242c3a1bfcfcc895ef29a','309743',$RandParam,"15334509852",0);
}